package com.platform.aop;

import com.alibaba.druid.filter.FilterAdapter;
import com.alibaba.druid.filter.FilterChain;
import com.alibaba.druid.proxy.jdbc.*;
import com.alibaba.druid.sql.SQLUtils;
import com.alibaba.druid.sql.ast.SQLStatement;
import com.alibaba.druid.sql.dialect.mysql.parser.MySqlStatementParser;
import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlSchemaStatVisitor;
import com.alibaba.druid.sql.parser.SQLStatementParser;
import com.alibaba.druid.stat.TableStat;
import com.alibaba.druid.util.JdbcConstants;
import com.alibaba.druid.wall.WallContext;
import com.platform.utils.MyBatisSqlUtils;
import com.platform.utils.StringUtils;
import com.platform.utils.ThreadLocalUtil;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by wangfei23 on 2018/11/22.
 */
public class DruidSqlFilter extends FilterAdapter {

    private final static String[] KEEP_SQL = new String[]{"SELECT", "INSERT", "UPDATE", "DELETE"};

    @Override
    public PreparedStatementProxy connection_prepareStatement(FilterChain chain, ConnectionProxy connection, String sql)
            throws SQLException {

        if (keep(sql)) {
            // 重新格式化SQL
            sql = MyBatisSqlUtils.rebuildSql(sql);
        }
        PreparedStatementProxy stmt = chain.connection_prepareStatement(connection, sql);
        return stmt;
    }

    private boolean keep(String sql) {
        if (StringUtils.isEmpty(sql)) return false;

        for (String s : KEEP_SQL) {
            if (sql.trim().toUpperCase().startsWith(s)) return true;
        }

        return false;
    }


}
